package com.fm.common.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.fm.common.R
import com.fm.common.databinding.ToolbarBinding
import java.lang.reflect.ParameterizedType

/**
 *
 * @Author:         ly2
 * @CreateDate:     2020/12/18
 * @Description:    base activity
 *
 */
abstract class BaseBPActivity<B : ViewBinding, P : BasePresenter<*>> : AppCompatActivity(), IView {
    protected lateinit var mContext: Context

    protected lateinit var binding: B

    protected var mPresenter: P? = null

    private var toolBarBinding: ToolbarBinding? = null

    //点击返回需要处理的东西
    private var leftListener: OnNavigationOnClickListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //用来修复安装后点击打开，home返回桌面重新打开app，打开新的引导页面，导致打开两个主页问题
        if (!isTaskRoot && intent != null) {
            val action = intent.action
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                finish()
                return
            }
        }
        mContext = this
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

        //初始化布局
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            try {
                @Suppress("UNCHECKED_CAST")
                val clzz: Class<B> = type.actualTypeArguments[0] as Class<B>
                val method = clzz.getMethod("inflate", LayoutInflater::class.java)
                @Suppress("UNCHECKED_CAST")
                binding = method.invoke(null, layoutInflater) as B
            } catch (e: Exception) {
                e.printStackTrace()
            }
            setContentView(binding.root)
        }

        onLoadPresenter()?.let {
            mPresenter = it
            it.attachView(this)
        }
        initView(savedInstanceState)
        initData()
    }

    //初始化view
    protected abstract fun initView(savedInstanceState: Bundle?)

    open fun initData() {}

    //初始化toolbar
    protected fun initToolbar(toolBarBinding: ToolbarBinding, @StringRes title: Int, showNavigationIcon: Boolean = true) {
        initToolbar(toolBarBinding, getString(title), showNavigationIcon)
    }

    protected fun initToolbar(toolBarBinding: ToolbarBinding, title: String, showNavigationIcon: Boolean = true) {
        toolBarBinding.toolbarTvTitle.text = title
        BarUtils.addMarginTopEqualStatusBarHeight(toolBarBinding.toolbar)
        setSupportActionBar(toolBarBinding.toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        if (showNavigationIcon) {
            toolBarBinding.toolbar.setNavigationIcon(R.drawable.nav_icon_back2)
            // Menu item click 的監聽事件一樣要設定在 setSupportActionBar 才有作用
            // toolbar.setOnMenuItemClickListener(onMenuItemClick);
            //设置toolbar左侧的点击事件
            toolBarBinding.toolbar.setNavigationOnClickListener {
                if (leftListener != null) {
                    leftListener?.onNavigationClick()
                } else {
                    finish()
                }
            }
        } else {
            toolBarBinding.toolbar.navigationIcon = null
        }
    }

    /**
     * 设置右侧文字内容
     */
    protected fun setRightInfo(
        toolBarBinding: ToolbarBinding,
        text: String = "",
        @DrawableRes image: Int? = null,
        listener: View.OnClickListener? = null
    ) {
        if (!StringUtils.isEmpty(text)) {
            toolBarBinding.toolbarItvRight.text = text
            toolBarBinding.toolbarItvRight.visibility = View.VISIBLE
        }
        image?.let {
            toolBarBinding.toolbarItvRight.setDrawable(ContextCompat.getDrawable(mContext, image)!!)
            toolBarBinding.toolbarItvRight.visibility = View.VISIBLE
        }
        toolBarBinding.toolbarItvRight.setOnClickListener(listener)
    }


    //设置返回按钮点击监听
    protected fun setLeftClickListener(listener: OnNavigationOnClickListener) {
        leftListener = listener
    }

    interface OnNavigationOnClickListener {
        fun onNavigationClick()
    }

    /**
     * 点击返回
     */
    override fun onBackPressed() {
        if (null != leftListener) {
            leftListener?.onNavigationClick()
        } else {
            super.onBackPressed()
        }
    }

    open fun onLoadPresenter(): P? {
        return null
    }


    override fun onDestroy() {
        super.onDestroy()
        ToastUtils.cancel()
        mPresenter?.detachView()
    }

    override fun bindToLife(): LifecycleOwner {
        return this
    }
}